package com.llkj.qingnianguoxue.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.NearPeopleAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.bean.NearPeopleBean;
import com.llkj.qingnianguoxue.bean.response.ResponseList;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.llkj.qingnianguoxue.circle.CircleOwnerDetailActivity.IS_REPORT;

/**
 * 附近的人
 */
public class NearPeopleFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener{
    public static final int REQUEST_CODE_ADD_FRIEND = 8901;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvNearPeople;
    private NearPeopleAdapter mNearAdapter;
    private List<NearPeopleBean> mNearData;
    private int totalSize, mPage,mCurrentPosition;

    public static NearPeopleFragment newInstance() {
        NearPeopleFragment fragment = new NearPeopleFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_near_people, container, false);
        EventBus.getDefault().register(this);
        initView();

        onRefresh();
        return rootView;
    }

    private void initView(){
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvNearPeople = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        lvNearPeople.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mNearData = new ArrayList<>();
        mNearAdapter = new NearPeopleAdapter(R.layout.item_near_people,mNearData);
        lvNearPeople.setAdapter(mNearAdapter);

        refreshLayout.setOnRefreshListener(this);
        mNearAdapter.setOnLoadMoreListener(this);

        lvNearPeople.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                NearPeopleBean item = mNearData.get(i);
                if(view.getId()== R.id.tv_add_friend){//加好友
                    Bundle bundle = new Bundle();
                    bundle.putString("uid",item.getId());
                    startActivityForResult(AppyVerificationActivity.class,bundle,REQUEST_CODE_ADD_FRIEND);
                }else if(view.getId()== R.id.iv_chat){//聊天
                    MyChatActivity.startSingleChat(getActivity(),item.getName(),item.getHx_id(),item.getHx_id());
                }
            }
        });
        lvNearPeople.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                NearPeopleBean item = mNearData.get(i);
                String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
                if(!uid.equals(item.getId())) {
                    //进入个人主页
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(IS_REPORT, false);
                    bundle.putString("ownerId",item.getId());
                    startActivity(CircleOwnerDetailActivity.class, bundle);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode == REQUEST_CODE_ADD_FRIEND){
            NearPeopleBean item = mNearData.get(mCurrentPosition);
            item.setIs_friend("2");
            mNearAdapter.notifyItemChanged(mCurrentPosition);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getNearPeople();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getNearPeople();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, mNearAdapter, null, lvNearPeople, totalSize);
    }

    private void getNearPeople(){
        HttpMethod.peopleNearby(getActivity(),this,String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_CIRCLE_PEOPLE_NEARBY) {//圈子成员
            try {
                ResponseList<NearPeopleBean> nearBean = GsonUtil.fromJsonList(data, NearPeopleBean.class);
                if (nearBean != null) {
                    try {
                        totalSize = Integer.parseInt(nearBean.getNum());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (mPage == 1) {
                        mNearData.clear();
                        LoadDataHelper.refreshComplete(mNearAdapter, mNearData, refreshLayout, lvNearPeople);
                    } else {
                        mNearAdapter.setEnableLoadMore(true);
                        mNearAdapter.loadMoreComplete();
                    }
                    mNearData.addAll(nearBean.getUser());
                    mNearAdapter.notifyDataSetChanged();
                    if (mNearData.size() == 0) {
                        ToastUtil.makeShortText(getActivity(), "没有找到附近的人");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        refreshLayout.setRefreshing(false);
    }
}
